//
//  String+Emoticon.swift
//  sinaweibo
//
//  Created by WGP on 16/4/24.
//  Copyright © 2016年 WGP. All rights reserved.
//

import UIKit

extension String
{
//    将微博中内容中的表情字符串替换成表情图片
    func emoticonNameTextToPicAttText() ->NSAttributedString
    {
        let attrText = NSMutableAttributedString(string: self)
        
        let pattern = "\\[.*?\\]"
        let regular = try! NSRegularExpression(pattern: pattern, options: .DotMatchesLineSeparators)
        
//        匹配
        let results = regular.matchesInString(self, options: [], range: NSRange(location: 0, length: self.characters.count))
        
//        反过来遍历,因为顺着匹配过后长度会变化
        for result in results.reverse()
        {
            let range = result.range
            
            let emoticonName = (self as NSString).substringWithRange(range)
            
            if let emoticonModel = HMEmoticonModel.emoticonNameToEmoticonModel(emoticonName)
            {
                let attrM = emoticonModel.emoticonModelToAttrText(UIFont.systemFontOfSize(15))
                
                attrText.replaceCharactersInRange(range, withAttributedString: attrM)
            }
        }
        return attrText
    }
}
